package cn.weekimwee.firstlineofcodeforkotlin.unit9

import android.os.Bundle
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_http_urlconnection.*
import java.io.BufferedReader
import java.io.InputStreamReader
import java.lang.Exception
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL

class HttpURLConnectionActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_http_urlconnection)
        send_requst.setOnClickListener {
            Thread({
                var connection: HttpURLConnection?= null
                var reader: BufferedReader?=null
                try {
                    val url = URL("http://www.baidu.com")
                    connection = url.openConnection() as HttpURLConnection
                    connection.requestMethod = "GET"
                    connection.connectTimeout = 8000
                    connection.readTimeout = 8000
                    var input = connection.inputStream
                    reader = BufferedReader(InputStreamReader(input))
                    var response = StringBuilder()
                    var isNotEmpty = true
                    while (isNotEmpty) {
                        var line = reader.readLine()
                        if (line != null) {
                            response.append(line)
                        } else {
                            isNotEmpty = false
                        }
                    }
                    runOnUiThread {
                        text.text = response
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                } finally {
                    reader?.close()
                    connection?.disconnect()
                }
            }).start()
        }
    }
}
